package com.labot.dao.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.labot.dao.Dbi18nDao;
import com.labot.dao.SearchException;
import com.labot.model.I18n;

/**
 * This class interacts with Hibernate session to save/delete and
 * retrieve Config objects.
 *
 * @author Ing. Enrique Barbeito
*/
@Repository("i18nDao")
public class Dbi18nDaoHibernate extends GenericDaoHibernate<I18n, Long> implements Dbi18nDao {

    /**
     * Constructor that sets the entity to User.class.
     */
    public Dbi18nDaoHibernate() {
        super(I18n.class);
    }

	@Override
	@SuppressWarnings(value="unchecked")
	public I18n getValue(String key) {
		List<I18n> lista = getSession().createCriteria(I18n.class).add(Restrictions.eq("key", key)).list();
		if (lista.isEmpty()) {
            return null;
        }
        return lista.get(0);
        
	}
	
	@Override
	@SuppressWarnings(value="unchecked")
	public List<I18n> search(String searchTerm) throws SearchException {
		if (searchTerm != null) {
			searchTerm = "%" + searchTerm + "%";
			Criteria criteria = getSession().createCriteria(I18n.class);
			
			Criterion rest1= Restrictions.ilike("key", searchTerm);
			Criterion rest2= Restrictions.ilike("en", searchTerm);
			Criterion rest3= Restrictions.ilike("es", searchTerm);
			
			criteria.add(Restrictions.or(rest1, rest2, rest3));
			
			return criteria.addOrder(Order.asc("key"))
									.list();
		} else {
			throw new SearchException("SearchTerm must not be NULL");
		}
	}


}
